package com.netintech.intelligenceInterface.iflytek.util;

import com.netintech.intelligenceInterface.common.StaticBean;
import com.netintech.intelligenceInterface.common.Type;
import com.netintech.intelligenceInterface.common.customException.InterfaceCallException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Date;
import java.util.Map;

import static com.netintech.intelligenceInterface.common.StaticBean.*;

/**
 * @author lining
 * @date 2021/4/29 15:32
 * 鉴权工具类
 */
public class AuthenticationUtil {

    public static boolean authentication(String httpMethod, String requestUrl, Map<String, String> headers) throws Exception {
        int length = SIGNATURE.length();
        String host = headers.get("host");
        String date = headers.get("date");
        String authorization = headers.get("authorization");
        //判断时间是否相差5分钟
        Date now = new Date();
        Date parse = LOCAL_DATE_FORMAT.get().parse(date);
        if ((Math.abs(now.getTime() - parse.getTime()) > StaticBean.FIVE_MINUTES_MILLISECONDS)) {
            throw new InterfaceCallException(Type.ERROR_PARAM, StaticBean.TIME_ERROR);
        }
        // 解析authorization 得到api_key 查询密钥apiSecret，得到sha
        //对api_key进行校验
        String apiKey = authorization.substring(authorization.indexOf(API_KEY_STR) + API_KEY_STR.length(), authorization.indexOf(ALGORITHM_STR));
        String apiSecret = "C68D62C5E68843F7AAD29F864B9C042";
        //从authorization解析sha
        String sha = authorization.substring(authorization.indexOf(SIGNATURE) + length).replaceAll("\"", "");
        URL url;
        url = new URL(requestUrl);
        Mac mac = Mac.getInstance(StaticBean.ALGORITHM_NAME);
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), StaticBean.ALGORITHM_NAME);
        mac.init(spec);
        String builder = "host: " + host + "\n" +
                "date: " + date + "\n" +
                httpMethod + " " + url.getPath() + " HTTP/1.1";
        byte[] hexDigits = mac.doFinal(builder.getBytes(StandardCharsets.UTF_8));
        String str = Base64.getEncoder().encodeToString(hexDigits);
        return sha.equals(str);
    }

}
